﻿using SqlScriptVault.Commands;
using SqlScriptVault.Model;
using SqlScriptVault.Properties;
using SqlScriptVault.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlScriptVault.ViewModel
{
    class ScriptViewModel : BaseNotifyViewModel
    {
        public ScriptViewModel()
        {
            ServerTypes = new List<ServerTypeChecker>(from serverType in new Settings().ServerTypes.Split('|') select new ServerTypeChecker { Checked = false, Text = serverType });
        }

        public Script Script { get; set; }

        public RelayCommand CommitCommand
        {
            get
            {
                return new RelayCommand(param => Commit());
            }
        }

        public List<ServerTypeChecker> ServerTypes { get; private set; }

        public event Action RequestClose;

        public void Initialize(string fileName)
        {
            FileNameService fileNameService = new FileNameService();
            string scriptName = fileNameService.GenerateScriptName(fileName);

            Script = new Script(fileName, scriptName);

            RaisePropertyChanged("Script");
        }

        public void Commit()
        {
            if (string.IsNullOrEmpty(Script.ScriptName))
            {
                return;
            }

            var selectedServerTypes = (from serverType in ServerTypes
                                       where serverType.Checked
                                       select serverType.Text).ToList();

            if (selectedServerTypes.Count() == 0)
            {
                return;
            }

            Script.ServerTypes = selectedServerTypes;

            RequestClose();
        }
    }
}
